<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { ref, reactive, onMounted } from "vue";
import Motion from "../utils/motion";
import { message } from "@/utils/message";
import type { FormInstance, FormRules } from "element-plus";
import { $t, transformI18n } from "@/plugins/i18n";
import { useUserStoreHook } from "@/store/modules/user";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Lock from "@iconify-icons/ri/lock-fill";
import { register } from "@/api/user";
import { useRouter } from "vue-router";
import { initRouter, getTopMenu } from "@/router/utils";
import { initUserPermission } from "@/utils/permission";
import { updateRules } from "../utils/rule";

const router = useRouter();
const { t } = useI18n();
const checked = ref(false);
const loading = ref(false);
const disabled = ref(false);
const ruleForm = reactive({
  email: "",
  nickName: "",
  password: "",
  repeatPassword: ""
});
const ruleFormRef = ref<FormInstance>();

const onUpdate = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  // if (checked.value) {
  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(ruleForm.email)) {
    message(transformI18n($t("login.pureEmailCorrectReg")), {
      type: "warning"
    });
    loading.value = false;
    return;
  }

  // 验证昵称不为空
  if (!ruleForm.nickName.trim()) {
    message("请输入昵称", {
      type: "warning"
    });
    loading.value = false;
    return;
  }

  if (ruleForm.password !== ruleForm.repeatPassword) {
    message(transformI18n($t("login.purePassWordDifferentReg")), {
      type: "error"
    });
    loading.value = false;
    return;
  }

  try {
    const result = await register({
      email: ruleForm.email,
      nickName: ruleForm.nickName,
      password: ruleForm.password
    });
    message(transformI18n($t("login.pureRegisterSuccess")), {
      type: "success"
    });

    // 注册成功后自动登录
    try {
      // 设置用户信息和token
      await useUserStoreHook().loginByUsername({
        email: ruleForm.email,
        password: ruleForm.password
      });

      // 初始化用户权限
      await initUserPermission();

      // 初始化路由并跳转到主页
      await initRouter().then(() => {
        disabled.value = true;
        router
          .push(getTopMenu(true).path)
          .then(() => {
            message(transformI18n($t("login.pureLoginSuccess")), {
              type: "success"
            });
          })
          .finally(() => (disabled.value = false));
      });
    } catch (error) {
      console.error("自动登录失败:", error);
      loading.value = false;
      // 如果自动登录失败，则回到登录页
      onBack();
    }
  } catch (error) {
    console.error(error);
    message("注册失败，请稍后再试", {
      type: "error"
    });
    loading.value = false;
  }
  // } else {
  //   loading.value = false;
  //   message(transformI18n($t("login.pureTickPrivacy")), {
  //     type: "warning"
  //   });
  // }
};

function onBack() {
  useUserStoreHook().SET_CURRENTPAGE(0);
}

const clearForm = () => {
  ruleForm.email = "";
  ruleForm.nickName = "";
  ruleForm.password = "";
  ruleForm.repeatPassword = "";
};

onMounted(() => {
  clearForm();
});
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="updateRules"
    size="large"
  >
    <Motion>
      <el-form-item prop="email">
        <el-input
          v-model="ruleForm.email"
          clearable
          autocomplete="off"
          placeholder="请输入邮箱"
          :prefix-icon="useRenderIcon('ri:mail-line')"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="100">
      <el-form-item prop="nickName">
        <el-input
          v-model="ruleForm.nickName"
          clearable
          autocomplete="off"
          placeholder="请输入昵称"
          :prefix-icon="useRenderIcon('ri:user-line')"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="200">
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          clearable
          show-password
          autocomplete="new-password"
          :placeholder="t('login.purePassword')"
          :prefix-icon="useRenderIcon(Lock)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="250">
      <el-form-item prop="repeatPassword">
        <el-input
          v-model="ruleForm.repeatPassword"
          clearable
          show-password
          autocomplete="new-password"
          :placeholder="t('login.pureSure')"
          :prefix-icon="useRenderIcon(Lock)"
        />
      </el-form-item>
    </Motion>
    <!-- 
    <Motion :delay="300">
      <el-form-item>
        <el-checkbox v-model="checked">
          {{ t("login.pureReadAccept") }}
        </el-checkbox>
        <el-button link type="primary">
          {{ t("login.purePrivacyPolicy") }}
        </el-button>
      </el-form-item>
    </Motion> -->

    <Motion :delay="350">
      <el-form-item>
        <el-button
          class="w-full"
          size="default"
          type="primary"
          :loading="loading"
          @click="onUpdate(ruleFormRef)"
        >
          {{ t("login.pureDefinite") }}
        </el-button>
      </el-form-item>
    </Motion>

    <Motion :delay="400">
      <el-form-item>
        <el-button class="w-full" size="default" @click="onBack">
          {{ t("login.pureBack") }}
        </el-button>
      </el-form-item>
    </Motion>
  </el-form>
</template>

<style scoped>
.el-button {
  --el-button-size: 40px;
}
</style>
